<template>
  <div class="flex flex-col h-full">
    <el-form :inline="true" :model="selectProps" class="demo-form-inline">
      <el-form-item>
        <el-input v-model="selectProps.title" placeholder="请输入公告名称" clearable />
      </el-form-item>
      <el-form-item>
        <el-input v-model="selectProps.content" placeholder="请输入公告内容" clearable />
      </el-form-item>
      <el-form-item>
        <el-button type="primary" @click="onSelect">搜索</el-button>
        <el-button type="danger" @click="deleteNotices">删除</el-button>
      </el-form-item>
    </el-form>
    <el-table class="flex-1 " :data="tableData" stripe style="width: 100%" @selection-change="handleSelectionChange">
      <el-table-column type="selection" width="55" :fixed="true"/>
      <el-table-column type="index" label="序号" width="80" :fixed="true" align="center" :index="TableIndexMethod"/>
      <el-table-column prop="title" label="标题" align="center"  show-overflow-tooltip/>
      <el-table-column prop="content" label="内容" align="center"  show-overflow-tooltip/>
      <el-table-column prop="userId" label="发布者" align="center">
        <template #default="scope">
          <span>
            {{userData.find((item) =>item.id == scope.row.userId)?userData.find((item) =>item.id == scope.row.userId).username:""}}
          </span>
        </template>
      </el-table-column>
      <el-table-column prop="createDate" label="发布时间" align="center" />
      <el-table-column label="操作" align="center">
        <template #default="scope">
          <el-button type="info" size="small" @click="getNoticeInfo(scope)">编辑</el-button>
          <el-button type="primary" size="small" @click="viewNoticeInfo(scope)">预览</el-button>
          <el-button type="danger" size="small" @click="deleteNotice([scope.row.id])">删除</el-button>
        </template>
      </el-table-column>

    </el-table>
    <el-pagination class="mt-2" v-model:current-page="tableProps.currentPage" v-model:page-size="tableProps.pageSize"
      :page-sizes="[15, 30]" layout="total, sizes, prev, pager, next, jumper" :total="tableProps.total"
      @size-change="handleSizeChange" @current-change="handleCurrentChange" />
  </div>
  <el-dialog v-model="noticeInfoVisible" :title="isReadonly?'信息预览':'信息修改'" width="550">
    <el-form ref="formRef" :inline="true" :model="noticeInfo" :rules="rules">
      <el-form-item prop="title" label="公告标题：" class="w-full ">
        <el-input v-model="noticeInfo.title" clearable :disabled="isReadonly"/>
      </el-form-item>
      <el-form-item prop="content" label="公告内容：" class="w-full ">
        <el-input v-model="noticeInfo.content" clearable type="textarea"  :autosize="{ minRows: 5 }" :disabled="isReadonly"/>
      </el-form-item>
      <el-form-item label="发布者：">
        <el-input v-model="noticeInfo.username" disabled  />
      </el-form-item>
    </el-form>
    <template #footer>
      <div class="dialog-footer" v-if="!isReadonly">
        <el-button @click="noticeInfoVisible = false">取消</el-button>
        <el-button type="primary" @click="handleDepInfoChange(formRef)">
          提交
        </el-button>
      </div>
    </template>
  </el-dialog>
</template>

<script lang="ts" setup>
import { ApiDelete, ApiPost, ApiPut } from '@/utils/Axios';
import { ElMessageBox, ElNotification, type FormInstance } from 'element-plus';
import { onBeforeMount, reactive, ref, watch } from 'vue'
const tableProps = ref({
  currentPage: 1,
  pageSize: 15,
  total: 30,
})
const selectProps = reactive({
  title: "",
  content: ""
})
const tableData = ref([])
const userData = ref([])
const multipleSelection = ref([])
const noticeInfo = ref({
  id: null,
  title: "",
  content: "",
  username:null
})
const noticeInfoVisible = ref(false)
const isReadonly = ref(false)
const formRef = ref<FormInstance>()

onBeforeMount(() => {
  getTableData(tableProps.value.currentPage, tableProps.value.pageSize)
  getUserData();
})

watch(tableProps, (newVal, oldVal) => {
  getTableData(newVal.currentPage, newVal.pageSize)
})

const TableIndexMethod = (index: number) => {
    return (tableProps.value.currentPage-1)*tableProps.value.pageSize+index+1
}

const getTableData = (currentPage, pageSize) => {
  ApiPost("/noticeInf/page", {
    page: Number(currentPage),
    pageSize: Number(pageSize),
    ...selectProps,
  }).then(res => {
    console.log(res)
    if (res.code === 200) {
      tableData.value = res.data.records
      tableProps.value.total = res.data.total
    } else {
      console.log("错误=>", res.msg);
    }
  }).catch(err => {
    console.log("错误=>", err);
  })
}

const getUserData = () => {
  ApiPost("/userInf/page", {
    page: 1,
    pageSize: 1000,
  }).then(res => {
    if (res.code === 200) {
      userData.value = res.data.records
    } else {
      console.log("错误=>", res.msg);
    }
  }).catch(err => {
    console.log("错误=>", err);
  })
}

const onSelect = () => {
  tableProps.value.currentPage = 1
  getTableData(tableProps.value.currentPage, tableProps.value.pageSize)
}

const deleteNotice = (noticeList: number[]) => {
  ElMessageBox({
    title: "警告",
    type: "warning",
    message: "确认删除该公告吗？",
    confirmButtonText: "确定",
    cancelButtonText: "取消",
    showCancelButton: true,
  }).then(() => {
    ApiDelete("/noticeInf/delete", { ids: noticeList.join(",") }).then(res => {
      if (res.code === 200) {
        getTableData(tableProps.value.currentPage, tableProps.value.pageSize)
        ElNotification({
          title: "删除成功",
          type: "success",
          showClose: false,
          duration: 2000,
        })
      } else {
        ElNotification({
          title: "删除失败",
          type: "error",
          message: res.msg,
          showClose: false,
          duration: 2000,
        })
      }
    }).catch((err) => {
      console.log("删除失败")
    })
  }).catch(() => {
    return
  })
}

const deleteNotices = () => {
  if (multipleSelection.value.length === 0) {
    return
  }
  const depList = multipleSelection.value.map(item => item.id)
  deleteNotice(depList)
}

const handleSelectionChange = (val) => {
  multipleSelection.value = val
}

const getNoticeInfo = (scope) => {
  noticeInfo.value = { ...scope.row,username:userData.value.find((item) =>item.id == scope.row.userId)?.username }
  noticeInfoVisible.value = true
  isReadonly.value = false
}
const viewNoticeInfo = (scope) => {
  noticeInfo.value = {...scope.row,username:userData.value.find((item) =>item.id == scope.row.userId)?.username }
  noticeInfoVisible.value = true
  isReadonly.value = true
}

const validateNoticetitle = (rule: any, value: any, callback: any) => {
  if (value === '') {
    callback(new Error('公告标题不能为空'))
  } else {
    callback()
  }
}

const validateNoticecontent = (rule: any, value: any, callback: any) => {
  if (value === '') {
    callback(new Error('公告内容不能为空'))
  } else {
    callback()
  }
}
const rules = reactive({
  title: [{ validator: validateNoticetitle, trigger: 'blur' }],
  content: [{ validator: validateNoticecontent, trigger: 'blur' }],
})

const handleDepInfoChange = (formEl: FormInstance | undefined) => {
  formEl.validate(vail => {
    if (vail && noticeInfo.value.id) {
      ElMessageBox({
        title: "提醒",
        type: "warning",
        message: "确认修改公告信息吗？",
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        showCancelButton: true,
      }).then(() => {
        const { id, title, content } = noticeInfo.value
        ApiPut("/noticeInf/update", { id, title, content }).then(res => {
          console.log(res)
          if (res.code === 200) {
            noticeInfoVisible.value = false
            getTableData(tableProps.value.currentPage, tableProps.value.pageSize)
            ElNotification({
              title: "修改成功",
              type: "success",
              showClose: false,
              duration: 2000,
            })
          }
        })
      }).catch(() => {
        return
      })
    }
  })

}

const handleSizeChange = (val) => {
  tableProps.value = { ...tableProps.value, pageSize: val };
};
const handleCurrentChange = (val) => {
  tableProps.value = { ...tableProps.value, currentPage: val };
};
</script>